package org.thingsboard.server.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.thingsboard.server.common.data.custom.DeviceGroup;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.custom.DeviceGroupId;
import org.thingsboard.server.dao.custom.DeviceGroupService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.custom.DeviceGroupActionService;
import org.thingsboard.server.service.security.permission.Operation;


/**
 * @desc 自定义分组接口开发
 * @author miki
 * @date 2022.03.17
 */
@RestController
@TbCoreComponent
@RequestMapping("/api")
public class DeviceGroupController extends BaseController {

    public static final String GROUP_ID = "groupId";
    private static final String GROUP_SECURITY_CHECK = "如果用户具有“租户管理员”权限，服务端将检查获取分组的拥有者是否属于同一租户。如果用户拥有“客户用户”权限，服务端将查询分组的操作者是否是该客户。";

    @Autowired
    private DeviceGroupService groupService;
    @Autowired
    private DeviceGroupActionService actionService;


    @ApiOperation(value = "获取分组 (getAlarmById)",
            notes = "通过分组id获取分组对象. " + GROUP_SECURITY_CHECK, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
    @GetMapping(value = "/group/{groupId}", produces = "application/json;charset=utf-8")
    public DeviceGroup getGroupById(@ApiParam(value = "表示分组id的字符串值。例如，“784f394c-42b6-435a-983c-b7beff2784f9”")
                              @PathVariable(GROUP_ID) String strGroupId) throws ThingsboardException {
        checkParameter(GROUP_ID, strGroupId);
        try {
            DeviceGroupId groupId = new DeviceGroupId(toUUID(strGroupId));
            return actionService.checkGroupId(groupId, Operation.READ);
        } catch (Exception e) {
            throw handleException(e);
        }
    }



}
